package com.googlecode.antilopebpm.instance;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.googlecode.antilopebpm.definition.ActivityDefinition;
import com.googlecode.antilopebpm.definition.ProcessDefinition;
import com.googlecode.antilopebpm.instance.activity.ActivityInstance;

public class ProcessInstance {

	private Long id;
	private String definitionId;
	private String name;
	private String creator;
	private String currentState;
	private ProcessDefinition processDefinition;

	private List<ActivityInstance> activities = new ArrayList<ActivityInstance>();

	private ProcessInstance() {

	}

	public ProcessInstance(ProcessDefinition processDefinition) {
		this.processDefinition = processDefinition;
	}

	public ProcessInstance(ProcessDefinition processDefinition, String creator) {
		this.create(processDefinition);
		this.creator = creator;
	}

	public void create(ProcessDefinition processDefinition) {
		this.definitionId = processDefinition.getId();
		this.name = processDefinition.getName();
		// TODO
		this.currentState = Constant.PROCESS_CREATED;
	}

	public void start() {
		this.start(null);
	}

	public void start(String activityDefinitionId) {

		if (activityDefinitionId == null) {
			// find
			// TODO
			ActivityDefinition activityDefinition = this.processDefinition
					.getActivityDefinitionById("a");
			ActivityInstance activityInstance = new ActivityInstance(this,
					activityDefinition);
			this.getActivities().add(activityInstance);
		} else {

		}
		// TODO
		this.currentState = Constant.PROCESS_STARTTED;
	}

	public String getDefinitionId() {
		return definitionId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public ProcessDefinition getProcessDefinition() {
		return processDefinition;
	}

	public String getCreator() {
		return creator;
	}

	public void setCreator(String creator) {
		this.creator = creator;
	}

	public List<ActivityInstance> getActivities() {
		return activities;
	}

	public Long getId() {
		return id;
	}

	public String getCurrentState() {
		return currentState;
	}

	public void setCurrentState(String currentState) {
		this.currentState = currentState;
	}

	public List<ActivityInstance> getActivitiesByCurrentState(
			String currentState) {
		List<ActivityInstance> activities = new ArrayList<ActivityInstance>();
		Iterator<ActivityInstance> it = this.activities.iterator();
		while (it.hasNext()) {
			ActivityInstance thisActivity = it.next();
			if (thisActivity.getCurrentState().equalsIgnoreCase(currentState)) {
				activities.add(thisActivity);
			}
		}
		return activities;
	}

	public void activityComplete(ActivityInstance activityInstance) {

	}
}
